<template>
  <div @keyup.enter="getAllData()">
    <el-form class="query-table-form" :inline="true">
      <el-form-item>
        <el-input v-model="params.customer_name" placeholder="项目名称查询" clearable>
          <i class="el-icon-search el-input__icon" slot="suffix" @click="getAllData()"></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          clearable
          :auto-top="true"
          @change="getAllData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <c-select
          clearable
          v-model="params['gua_type.eq']"
          placeholder="业务模式"
          :options="enumGuaType"
          @change="getAllData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="params['is_history.eq']"
          clearable
          placeholder="是否是历史数据"
          :options="{
            0: '否',
            1: '是',
          }"
          @change="getAllData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-form-item>
          <c-select
            v-model="seachParams"
            clearable
            placeholder="项目状态"
            :options="searchOptions"
            @change="setSeachParams"
          ></c-select>
        </el-form-item>
      </el-form-item>

      <el-form-item>
        <el-input v-model="params.mobile_no" placeholder="电话号码查询" clearable>
          <i class="el-icon-search el-input__icon" slot="suffix" @click="getAllData()"></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getAllData()">查询</el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('项目受理')"
        >
          导出
        </el-button>
      </el-form-item>
      <el-form-item class="float-right">
        <el-button @click="handleAdd()" icon="el-icon-plus">新增项目</el-button>
      </el-form-item>
      <div class="text-muted" v-loading="countLoading">
        <div>合计：</div>
        申请金额：
        <span class="text-primary">{{ countData.p || '-' }}</span>
        万元 。放款金额：
        <span class="text-primary">{{ countData.p1 || '-' }}</span>
        万元 。在保余额：
        <span class="text-primary">{{ countData.p2 || '-' }}</span>
        万元 。
      </div>
    </el-form>
    <small class="text-warning">在担保意向函盖章前都可在此处修改项目基本信息</small>
    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData">
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>
      <template v-slot:status="scope">
        <el-popover
          v-if="+scope.row.confuse_status === 3"
          placement="top-start"
          title="拒绝理由"
          width="200"
          trigger="hover"
          :content="scope.row.confuse_des"
        >
          <div slot="reference" class="badge" :class="`badge-${scope.row.statusStyle}`">
            {{ scope.row.statusLable }}
          </div>
        </el-popover>

        <div v-else class="badge" :class="`badge-${scope.row.statusStyle}`">
          {{ scope.row.statusLable }}
        </div>
      </template>
      <template v-slot:name="scope">
        <el-popover placement="top-start" title="项目经理" trigger="hover">
          <div>
            <div>{{ `A角： ${scope.row.res_a_name || '-'}；` }}</div>
            <div class="mb-2">{{ `电话： ${scope.row.res_a_phone || '-'}` }}</div>
            <div>{{ `B角： ${scope.row.res_b_name || '-'}；` }}</div>
            <div>{{ `电话： ${scope.row.res_b_phone || '-'}` }}</div>
          </div>
          <div slot="reference">
            <div class="status-label badge-info text-left w-100">
              <div>A角:{{ scope.row.res_a_name }}</div>
              <div>B角:{{ scope.row.res_b_name }}</div>
            </div>
          </div>
        </el-popover>
      </template>
      <template v-slot:guaType="scope">
        <div>{{ scope.row.guaType }}</div>
        <div
          v-if="scope.row.channel_type"
          class="badge"
          :class="+scope.row.channel_type ? 'badge-warning' : 'badge-info'"
        >
          {{ enumChannelType[scope.row.channel_type] }}
        </div>
      </template>
      <template v-slot:status="scope">
        <el-popover
          v-if="+scope.row.confuse_status === 3"
          placement="top-start"
          title="拒绝理由"
          width="200"
          trigger="hover"
          :content="scope.row.confuse_des"
        >
          <div slot="reference" class="badge" :class="`badge-${scope.row.statusStyle}`">
            {{ scope.row.statusLable }}
          </div>
        </el-popover>

        <div v-else class="badge" :class="`badge-${scope.row.statusStyle}`">
          {{ scope.row.statusLable }}
        </div>
      </template>
      <template v-slot:result="scope">
        <div class="badge" :class="`badge-${scope.row.scanBlackResultStyle}`">
          {{ scope.row.scanBlackResultLabel }}
        </div>
      </template>
      <template v-slot:letter="scope">
        <span v-if="!scope.row.docId">未生成</span>
        <div v-else @click="showLetter(scope.row)" class="badge badge-success cursor-pointer">
          查看
        </div>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getAllData"
      ></el-pagination>
    </div>

    <el-dialog
      :visible.sync="reportVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="80%"
    >
      <el-tabs v-model="active">
        <el-tab-pane label="项目信息" name="first">
          <info-view :related-data="relatedData"></info-view>
        </el-tab-pane>
        <el-tab-pane label="申请表" v-if="+relatedData.form_type === 1">
          <apply-table :query-id="queryId"></apply-table>
        </el-tab-pane>
        <el-tab-pane label="附件">
          <attach-view :query-id="queryId" :visible="reportVisible"></attach-view>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <new-project
      :visible.sync="visible"
      @success="getAllData()"
      :query-id="relatedId"
    ></new-project>
    <el-dialog :visible.sync="letterVisible" width="840px" :before-close="beforeClose">
      <letter-view :query-id="letterQueryId"></letter-view>
    </el-dialog>

    <edit-project
      :visible.sync="editVisible"
      :query-id="editId"
      @success="getAllData()"
    ></edit-project>

    <handler-approval-dialog
      :visible.sync="approvalVisible"
      :query-id="approvalId"
      @success="getAllData()"
    ></handler-approval-dialog>

    <attach-dialog
      :visible.sync="attachVisible"
      :query-id="attachRelatedId"
      :bank-id="attachBankId"
    ></attach-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import {
  enumGuaType,
  enumProjectType,
  enumChannelType,
  enumScanBlackStatus,
  enumSubmitType,
} from '@/bigcredit/views/program/enum'
import SelectAddress from '@/components/select/SelectAddress'
import AttachView from '@/credit/components/AttachView'
// import CreditFile from '@/credit/components/creditFile/CreditCard'
// import RecommendFile from '@/credit/views/city/program/RecommendFile'
// import ApprovalEdit from '@/credit/views/city/program/ApprovalEdit'
import taskTableMixin from '@/credit/mixin/self/taskTable'
import NewProject from '@/bigcredit/views/program/components/new/NewProjectDialog'
import EditProject from '@/bigcredit/views/program/components/new/EditProject'
import InfoView from '@/bigcredit/views/program/components/Info'
import LetterView from '@/credit/views/county/unionProvince/components/LetterView'

import { searchOptions } from '@/cadmin/views/org/CreditCount'
import HandlerApprovalDialog from '@/bigcredit/views/program/components/new/HandlerApprovalDialog'
import AttachDialog from '@/bigcredit/views/program/components/new/AttachDialog'
import ApplyTable from '@/bigcredit/views/program/components/apply/ApplyTable'
export default {
  components: {
    SelectAddress,
    // CreditFile,
    AttachView,
    // ApprovalEdit,
    // RecommendFile,
    NewProject,
    InfoView,
    LetterView,
    EditProject,
    HandlerApprovalDialog,
    AttachDialog,
    ApplyTable,
  },
  mixins: [taskTableMixin],
  props: {},
  data() {
    return {
      searchOptions,
      enumGuaType,
      enumChannelType,
      order: {
        N1is_history: 'asc',
        N2Create_time: 'desc',
        N3approved_date: 'desc',
      },
      params: {
        index: 1,
        size: 15,
        'recommend_status.eq': 1,
        'gua_type.neq': 3,
        subKey: 'ele_letter_info.customer_related_id',
        // 'claim_status.eq': '1'
      },
      editRow: {},
      queryId: '',
      reportVisible: false,
      exportLoading: false,
      relatedData: {},
      // tableName: 'customer_related',
      tableData: [],
      tableColumns: [
        {
          attrs: { label: '客户名称', prop: 'customer_name', minWidth: '110px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '项目类型', prop: 'projectType', align: 'center' } },
        { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
        // { attrs: { label: 'address_code', prop: 'address_code', align: 'center' } },
        { attrs: { label: '负责人', prop: 'corp_name', align: 'center' } },
        { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center' } },
        { attrs: { label: '申请金额(万元)', prop: 'apply_funds', align: 'center' } },
        { attrs: { label: '创建时间', prop: 'createTime', align: 'center', width: 100 } },
        { attrs: { label: '项目来源', prop: 'projectRescource', align: 'center' } },
        { attrs: { label: '项目经理', prop: 'resName', width: 100 }, slot: 'name' },
        {
          attrs: { label: '业务模式', prop: 'guaType', align: 'center' },
          slot: 'guaType',
        },
        // {
        //   attrs: { label: '扫黑结果', prop: 'scanBlackResultLabel', align: 'center', width: 110 },
        //   slot: 'result',
        // },
        { attrs: { label: '项目状态', prop: 'statusLable', align: 'center' }, slot: 'status' },
        {
          attrs: { label: '担保意向函', prop: 'letterStatusLabel', align: 'center' },
          slot: 'letter',
        },
        {
          attrs: { label: '操作', align: 'center', width: 140 },
          operations: [
            {
              content: '受理',
              icon: 'fa fa-legal',
              event: this.handlerApproval,
              ifRender: row => +row.is_approval <= 0 && row.service_id === this.clientId,
            },
            {
              content: '修改基本信息',
              icon: 'fa fa-edit',
              event: this.handleEdit,
              ifRender: row =>
                (+row.confuse_status !== 3 || +row.is_history === 1) &&
                row.service_id === this.clientId,
            },
            {
              content: '上传附件',
              icon: 'fa fa-clipboard',
              event: this.hanleAttach,
              ifRender: row => row.service_id === this.clientId,
            },
            { content: '查看', icon: 'fa fa-search', event: this.handleView },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger' },
              event: this.handleDelete,
              ifRender: row => [0, 2].includes(+(row.is_approval || '')),
            },
            // {
            //   content: '合同处理',
            //   icon: 'fa fa-file-text',
            //   event: this.handleContract,
            //   ifRender: row =>
            //     [row.res_a, row.res_b, row.res_user_id_risk_point].includes(this.userId),
            // },
          ],
        },
      ],
      statusIndex: -1,
      cellStyles: {},
      visible: false,
      relatedId: '',
      letterVisible: false,
      letterQueryId: '',
      seachParams: '',
      otherParams: {},
      countData: {},
      countLoading: false,

      editVisible: false,
      editId: '',

      approvalVisible: false,
      approvalId: '',

      attachVisible: false,
      attachRelatedId: '',
      attachBankId: '',
      active: 'first',
    }
  },
  computed: {
    ...mapGetters(['user', 'userId', 'job']),
    // isShowAllJob() {
    //   return projectShowJobs.includes(this.job)
    // }
  },
  watch: {},
  created() {
    this.params['orWhere.service_id.eq'] = this.clientId
    this.params['orWhere.gua_service_id.eq'] = this.clientId
    // if (!this.isShowAllJob) {
    //   this.params['orWhere.res_a.eq'] = this.userId
    //   this.params['orWhere.res_b.eq'] = this.userId
    // }

    this.getAllData()
  },
  mounted() {},
  methods: {
    showLetter(row) {
      if (row.docId) {
        this.letterVisible = true
        this.letterQueryId = row.customer_related_id
      }
    },
    beforeClose() {
      this.letterVisible = false
      this.letterQueryId = ''
    },
    // 删除
    handleDelete(row) {
      this.$utils
        .msgbox({
          message: `确定删除：${row.customer_name}?`,
          beforeClose: () =>
            this.$api.relatedDelete(this.$serviceName, {
              masterTableInfo: JSON.stringify({
                customer_related_id: row.customer_related_id,
              }),
              masterTableName: 'customer_related',
              slaveTableName: 'comm_loan_person',
            }),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.getData()
        })
        .catch(err => this.$message.error(err?.data?.error_description ?? '删除失败，请重试！'))
    },

    hanleAttach(row) {
      this.attachVisible = true
      this.attachRelatedId = row.customer_related_id
      this.attachBankId = row.bank_id || ''
    },

    handlerApproval(row = {}) {
      this.approvalVisible = true
      this.approvalId = row.customer_related_id ?? ''
    },
    getAllData(a = 1) {
      this.getData(a)
      const { index, size, subKey, ...params } = this.getParams()
      this.getCountData(params)
    },
    getCountData(params) {
      const search = {
        ...params,
        groupFunc: 'round(sum(apply_funds)|2),round(sum(reply_funds)|2),round(sum(left_funds)|2)',
      }
      this.countLoading = true
      this.$api
        .getData(this.$serviceName, this.tableName, search)
        .then(res => {
          this.countData = res?.data?.[0] ?? {}
        })
        .finally(() => {
          this.countLoading = false
        })
    },
    getParams() {
      return {
        ...this.params,
        ...this.otherParams,
      }
    },
    setSeachParams(a) {
      const data = this.searchOptions.find(item => item.value === a) || {}
      this.otherParams = data.params || {}
      this.getAllData()
    },

    handleAdd(row) {
      this.visible = true
      this.relatedId = row ? row.customer_related_id : ''
    },

    handleEdit(row) {
      this.editVisible = true
      this.editId = row ? row.customer_related_id : ''
    },
    dataAdapter(item) {
      if (+item.confuse_status === 3) {
        item.statusLable = '已拒绝'
        item.statusStyle = 'danger'
      } else {
        item.statusLable = +item.is_approval === 0 ? '未受理' : '已受理'
        item.statusStyle = +item.is_approval === 0 ? 'info' : 'success'
      }
      item.projectSouce = (item.submit_client_name || '') + (item.submit_person_name || '')
      item.createTime = this.$utils.dateFormat(
        item.recommend_time || item.create_time,
        'yyyy.MM.dd'
      )
      item.projectType = enumProjectType[item.project_type] || '-'
      item.guaType = enumGuaType[item.gua_type]
      item.resName = `A角: ${item.res_a_name} B角: ${item.res_b_name}`

      const sacnBlackResult = enumScanBlackStatus[item.scan_black_result] || {}
      item.scanBlackResultLabel = sacnBlackResult.label || '-'
      item.scanBlackResultStyle = sacnBlackResult.style || '-'

      item.projectRescource =
        +item.submit_type === 2 ? item.submit_person_name : enumSubmitType[item.submit_type]

      const letters = (item?.ele_letter_info ?? []).filter(item => +item.ele_letter_type === 1)
      const normalLetter = letters.sort((a, b) => a.sign_status - b.sign_status)
      item.docId = normalLetter?.[0]?.doc_id || ''
      return item
    },

    handleView(row) {
      this.active = 'first'
      this.queryId = row.customer_related_id
      this.reportVisible = true
      this.relatedData = row
    },
  },
}
</script>
<style scoped>
.decoration {
  text-decoration: line-through;
}
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
